<!--
 * @Description: File Description
 * @Author: jundie.cheng@hand-china.com
 * @version: H3.0
 * @Date: 2023-03-29 09:32:12
 * @LastEditTime: 2023-03-29 09:43:26
-->
<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>
          {{
            type === -1 ? $t('BIWD.AddFavorite.Navigate.Add.Title') : $t('BIWD.AddFavorite.Navigate.Edit.Title')
          }}</view
        >
      </HeaderLayout>
    </template>
    <view class="add-favorite-view">
      <!-- 我的收藏 -->
      <view class="favoriteName">
        <text>{{ favoriteName }}</text>
        <image @click="showEditNameView" class="img" :src="'/pages/appliance/static/Rename_icon.png'"></image>
      </view>
      <!-- 选择图片 -->
      <view class="pictureTip">
        <view class="swiperView" :style="isBOSCHBIWD ? 'height: 300rpx;' : 'height: 240rpx;'">
          <view
            class="swiperItemView"
            v-for="(item, index) in favoritePictureList"
            :key="index"
            @touchstart="touchTeaImageStart"
            @touchmove="touchTeaImageMove"
            @touchend="touchTeaImageEnd"
            @click="clickTeaImage(index)"
          >
            <image
              v-if="item.url"
              :class="{
                swiperItemChooseView: index === currentIndex,
                [`swiperItemImage${(item.position || 0) < 5 ? item.position : ''}`]: true,
              }"
              :src="`${imgUrl}${item.url}`"
            >
              {{ item.index }}</image
            >
            <view :class="`swiperItemFont${(item.position || 0) < 5 ? item.position : ''}`" v-if="isBOSCHBIWD">{{
              item.name
            }}</view>
          </view>
        </view>
      </view>
      <view class="favoriteView">
        <!-- 选择温度  -->
        <view class="favoriteBox">
          <view class="favoriteViewTitle">{{ $t('BIWD.AddFavorite.Temperatures.Label') }}<text>(℃)</text></view>
          <view
            :style="opcityJianOne === 0 ? 'opacity:0.3' : 'opacity:1'"
            @click="reduceCurIndex"
            class="pickerViewLeft"
          >
            <image :src="'/pages/appliance/static/ic_decrease_icon.png'"></image>
          </view>
          <picker-view
            mask-class="maskStyle"
            indicator-style="height: 46px;"
            indicator-class="clearBorder"
            class="pickerView"
            :value="curIndex"
            @change="chooseTempCurIndex"
            @pickstart="startPick"
            @pickend="endPick"
          >
            <picker-view-column>
              <view
                class="pickerItem"
                v-for="(item, index) in temperatures"
                :key="index"
                :class="{ active: index === curIndex[0] }"
                style="line-height: 50px; text-align: center"
              >
                {{ item.value }}</view
              >
            </picker-view-column>
          </picker-view>
          <view
            :style="opcityJiaOne === temperatures.length - 1 ? 'opacity: 0.3' : 'opacity: 1'"
            @click="addCurIndex"
            class="pickerViewRight"
          >
            <image :src="'/pages/appliance/static/ic_add_icon.png'"></image>
          </view>
        </view>
        <!-- 选择容量  -->
        <view class="favoriteBox">
          <view class="favoriteViewTitle">{{ $t('BIWD.AddFavorite.Mill.Label') }} <text>(ml)</text></view>
          <view
            :style="opcityJianTwo == 0 ? 'opacity:0.3' : 'opacity:1'"
            @click="reduceMilliliter"
            class="pickerViewLeft"
          >
            <image :src="'/pages/appliance/static/ic_decrease_icon.png'"></image>
          </view>
          <picker-view
            mask-class="maskStyle"
            indicator-style="height: 46px;"
            indicator-class="clearBorder"
            class="pickerView"
            :value="millIndex"
            @change="chooseTempMilliliter"
          >
            <picker-view-column>
              <view
                class="pickerItem"
                v-for="(item, index) in milliliter"
                :key="index"
                :class="{ active: index === millIndex[0] }"
                style="line-height: 50px; text-align: center"
              >
                {{ item.value }}</view
              >
            </picker-view-column>
          </picker-view>
          <view
            :style="opcityJiaTwo == milliliter.length - 1 ? 'opacity:0.3' : 'opacity:1'"
            @click="addMilliliter"
            class="pickerViewRight"
          >
            <image :src="'/pages/appliance/static/ic_add_icon.png'"></image>
          </view>
        </view>
      </view>
    </view>
    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton @click="saveFavorite">
          <TrackButton
            track-id="Navigation.Appliance.BIWD.MyFavorite.SaveFavorite.Button.text"
            :type="TrackType.ApplianceDetail"
            :track-data="trackData"
          >
            <view class="footer-box" @click="saveFavorite">{{ $t('BIWD.AddFavorite.Save.Button.Text') }}</view>
          </TrackButton>
        </ActionButton>
      </FooterLayout>
    </template>

    <!-- 错误提示弹框 -->
    <Modal v-model:visible="isShowErrorView" title="提示" ok-text="知道了" @ok="hideErrorView">
      <view class="lineDes">{{ errorText }}</view>
    </Modal>
    <RenameModal
      :title="$t('BIWD.AddFavorite.Favorite.Dialog.Title')"
      :ok-text="$t('BIWD.AddFavorite.Favorite.Dialog.Confirm.Text')"
      :cancel-text="$t('BIWD.AddFavorite.Favorite.Dialog.Cancel.Text')"
      v-model:show="renamePopFlag"
      :nick-name="nickname"
      :name-focus="nameFocus"
      input-type="biwdAddFavorite"
      :no-repeat-list="savedFavoriteNameArray"
      @confirm="confirmRename"
    ></RenameModal>
  </PageLayout>
</template>
<script lang="ts">
export type FavoritePictureListType = {
  index?: number
  name?: string
  position?: number
  url: string
}
export type FavoritePictureListTypeOther = FavoritePictureListType & {
  nameZH?: string
}
export type PickerType = {
  value: number
}
</script>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import Modal from '@/common/modal.vue'
import RenameModal from '@/common/renameModal.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import netconfig from '@/config/netconfig'
import { useApplianceStore } from '@/store/appliance'
import { favoritePictureListBOSCH, favoritePictureListSIEMENS, NameToArray } from '../filterStatusList'
import { onLoad } from '@dcloudio/uni-app'
import type { FavouriteListTypeData, submitDataType, submitSettingType } from '../favoriteList/favoriteList.vue'
import { setHomeAppliancePrograms, setHomeApplianceSettings } from '@/api/appliance'
import TrackButton from '@/dataReport/components/TrackButton.vue'
import { trackEvent, TrackType } from '../../../../dataReport/tracks'

import {
  DatConfig,
  DatConfig_SetCollect,
  CollectionOperation,
  CollectionOperation_Add,
  DatConfig_AddCollect,
  CollectionOperation_Edit,
  DatConfig_EditCollect,
} from '@/constants/WDCommand'
import { actionDebounce, useEventReceiver } from '@/utils/mpHelper'
import { useI18n } from 'vue-i18n'
import type { BIWDController } from '@/controller/BIWD/definition'
import { safeTrack } from '@/dataReport/dataReportUtil'

const applianceStore = useApplianceStore()
const control = ref<BIWDController.Control | null>(null)
useEventReceiver('control', (received: BIWDController.Control) => {
  control.value = received
})
const headerStyle = {
  backgroundColor: '#fff',
}
const temperaturesList: PickerType[] = []
for (let i = 35; i <= 95; i++) {
  temperaturesList.push({
    value: i,
  })
}
let milliliterList: PickerType[] = []
for (let i = 100; i <= 1000; ) {
  milliliterList.push({
    value: i,
  })
  i = i + 10
}

const i18n = useI18n()

const imgUrl = netconfig.ASSETSPRE_ICONS
let isrun = false
let iscount = false
let startPoint: Touch
let pickState = false
let favoriteChangeInCallSaveApi = false //在调取保存收藏的API中收到收藏变更弹窗

const trackData = ref({})
const haId = ref('')
const isBOSCHBIWD = computed(() => haId.value.split('-')[0].toUpperCase() !== 'SIEMENS')

const favoriteName = ref('') //收藏名字
const currentIndex = ref(0) //当前选择图片
const favoritePictureList = ref<FavoritePictureListType[]>([])
const favoriteList = ref<FavouriteListTypeData[]>([])
const type = ref(-1) //-1 新增 >0编辑
const nameError = ref('')
const savedFavoriteNameArray = ref<string[]>([])
const curIndex = ref([0]) // 当前温度值下标
const temperatures = computed<PickerType[]>(() => temperaturesList) //温度
const opcityJianOne = ref(0) //温度减号默认模糊度
const opcityJiaOne = ref(0) //温度加号默认模糊度
const opcityJianTwo = ref(0) //容量减号默认模糊度
const opcityJiaTwo = ref(0) //容量加号默认模糊度
const millIndex = ref([0]) // 当前毫升下标
const milliliter = computed<PickerType[]>(() => milliliterList) //毫升
const isShowErrorView = ref(false)
const errorText = ref('')
const isShowFavoriteUpdateView = ref(false) // 是否展示收藏变更弹窗
const oldFavoriteName = ref('') //待修改的收藏详情
const oldFavoriteTemp = ref('') //待修改的收藏详情
const oldFavoriteVol = ref('') //待修改的收藏详情
const oldFavoritePic = ref('') //待修改的收藏详情
const isCallSaveApi = ref(false)
const isCallApi = ref(false)
const isVirtual = ref(false)

onLoad((query: any) => {
  haId.value = query?.haId
  type.value = Number(query?.index)
  isVirtual.value = query?.isVirtual === 'true'
  favoriteList.value = JSON.parse(decodeURIComponent(query?.favoriteList))
  getFavoriteListNameFun(favoriteList.value)
  if (type.value != -1) {
    showOldFavoriteData()
  } else {
    favoriteName.value = getFavoriteName()
  }
  initImageList(currentIndex.value)
})
/**
 * 获取所有收藏名称
 * @param favoriteList
 */
function getFavoriteListNameFun(favoriteList: FavouriteListTypeData[]) {
  for (let i = 0; i < favoriteList.length; i++) {
    if (i !== type.value) {
      savedFavoriteNameArray.value.push(favoriteList[i].name)
    }
  }
}
/**
 * 获取收藏列表
 * @param index
 */
function initImageList(index: number) {
  let list: FavoritePictureListType[] = []
  let newFilterStatusList: FavoritePictureListTypeOther[] = isBOSCHBIWD.value
    ? favoritePictureListBOSCH
    : favoritePictureListSIEMENS
  if (index < 0) {
    index = index + newFilterStatusList.length
  }
  if (index > newFilterStatusList.length - 1) {
    index = index - newFilterStatusList.length
  }

  for (var i = 0; i < newFilterStatusList.length; i++) {
    //当前后一个的后面所有
    let position = i - index + 2
    if (position > newFilterStatusList.length - 1) {
      position = position - newFilterStatusList.length
    }
    if (position < 0) {
      position = position + newFilterStatusList.length
    }
    list.push({
      url: newFilterStatusList[i].url,
      index: i,
      name: isBOSCHBIWD ? (newFilterStatusList[i].nameZH as string) : '',
      position: position,
    })
  }
  favoritePictureList.value = list
  currentIndex.value = index
}
/**
 * 显示需要编辑收藏的数据
 */
function showOldFavoriteData() {
  oldFavoriteName.value = favoriteList.value[type.value].name
  oldFavoriteTemp.value = favoriteList.value[type.value].fav_temp
  oldFavoriteVol.value = favoriteList.value[type.value].fav_vol
  oldFavoritePic.value = favoriteList.value[type.value].fav_pic
  favoriteName.value = oldFavoriteName.value
  temperatures.value.forEach((item, index) => {
    if (item.value === Number(oldFavoriteTemp.value)) {
      curIndex.value[0] = index
    }
  })
  for (let j = 0; j < milliliter.value.length; j++) {
    if (milliliter.value[j].value === Number(oldFavoriteVol.value) * 10) {
      millIndex.value[0] = j
    }
  }
  changeJiaJian(curIndex.value[0], 't')
  changeJiaJian(curIndex.value[0], 'm')
  currentIndex.value = Number(oldFavoritePic.value)
}
/**
 * 获取新增收藏程序名称
 */
function getFavoriteName() {
  let nameArray = []
  let existArray = []
  if (!isBOSCHBIWD.value) {
    nameArray = [
      '我的收藏1',
      '我的收藏2',
      '我的收藏3',
      '我的收藏4',
      '我的收藏5',
      '我的收藏6',
      '我的收藏7',
      '我的收藏8',
      '我的收藏9',
    ]
    existArray = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    for (let i = 0; i < favoriteList.value.length; i++) {
      let name = favoriteList.value[i].name
      let index = nameArray.indexOf(name)
      if (index != -1) {
        existArray[index] = 1
      }
    }
  } else {
    let newfavoriteName = favoritePictureListBOSCH[currentIndex.value].nameZH
    for (let i = 0; i < favoritePictureListBOSCH.length; i++) {
      if (i == 0) {
        nameArray.push(newfavoriteName)
      } else {
        nameArray.push(newfavoriteName + i)
      }
      existArray.push(0)
    }
    for (let i = 0; i < favoriteList.value.length; i++) {
      let name = favoriteList.value[i].name
      let index = nameArray.indexOf(name)
      if (index != -1) {
        existArray[index] = 1
      }
    }
  }
  let existIndex = existArray.indexOf(0)
  if (type.value != -1 && existIndex == -1) {
    return favoriteName.value
  } else {
    return nameArray[existIndex]
  }
}
/**
 * 开始滑动茶杯图片
 * @param e
 */
function touchTeaImageStart(e: TouchEvent) {
  isrun = true
  startPoint = e.touches[0]
}
/**
 * 滑动茶杯图片
 * @param e
 */
function touchTeaImageMove(e: TouchEvent) {
  if (iscount == true || isrun == false) return
  iscount = true
  var endPoint = e.touches[e.touches.length - 1]
  var translateX = endPoint.clientX - startPoint.clientX
  //向右滑动
  if (translateX > 0) {
    let moveIndex = Math.round(translateX / 100)
    if (moveIndex > 0) {
      initImageList(currentIndex.value - moveIndex)
      startPoint = endPoint
    }
    iscount = false
  } else {
    let moveIndex = Math.round(-translateX / 100) == undefined ? 0 : Math.round(-translateX / 100)
    if (moveIndex > 0) {
      initImageList(Number(currentIndex.value) + Number(moveIndex))
      startPoint = endPoint
    }
    iscount = false
  }
}
/**
 * 结束滑动茶杯图片
 */
function touchTeaImageEnd() {
  isrun = false
  if (type.value === -1) favoriteName.value = getFavoriteName()
}
/**
 * 点击茶杯的图片
 * @param e
 */
function clickTeaImage(index: number) {
  if (index === currentIndex.value) {
    return
  }
  initImageList(index)
  if (type.value === -1) favoriteName.value = getFavoriteName()
}
/**
 * 选择温度
 * @param e
 */
function chooseTempCurIndex(e: WechatMiniprogram.PickerChange) {
  const indexes = e.detail.value as number[]
  changeJiaJian(indexes[0], 't')
  curIndex.value = indexes
}
/**
 * 减少温度
 */
function reduceCurIndex() {
  let index = curIndex.value[0] - 1
  index = index >= 0 ? index : 0
  changeJiaJian(index, 't')
  curIndex.value = [index]
}
/**
 * 增加温度
 */
function addCurIndex() {
  let index = curIndex.value[0] + 1
  index = index <= temperatures.value.length - 1 ? index : temperatures.value.length - 1
  changeJiaJian(index, 't')
  curIndex.value = [index]
}
/**
 * 当滚动选择开始时候触发事件
 */
function startPick() {
  pickState = true
}
/**
 * 当滚动选择结束时候触发事件
 */
function endPick() {
  pickState = false
}
/**
 * 选择容量
 * @param e
 */
function chooseTempMilliliter(e: WechatMiniprogram.PickerChange) {
  const indexes = e.detail.value as number[]
  changeJiaJian(indexes[0], 'm')
  millIndex.value = indexes
}
/**
 * 减少容量
 */
function reduceMilliliter() {
  let index = millIndex.value[0] - 1
  index = index >= 0 ? index : 0
  changeJiaJian(index, 'm')
  millIndex.value = [index]
}
/**
 * 增加容量
 */
function addMilliliter() {
  let index = millIndex.value[0] + 1
  index = index <= milliliter.value.length - 1 ? index : milliliter.value.length - 1
  changeJiaJian(index, 'm')
  millIndex.value = [index]
}
/**
 * 监听滑动改变温度或容量时加减号透明度改变
 * @param index
 * @param type
 */
function changeJiaJian(index: number, type: string) {
  // t表示温度 m标识容量
  if (type == 't') {
    opcityJianOne.value = index
    opcityJiaOne.value = index
  } else {
    opcityJianTwo.value = index
    opcityJiaTwo.value = index
  }
}
/**
 * 保存收藏列表
 */
const saveFavorite = actionDebounce({
  call: async () => {
    if (isVirtual.value) {
      uni.showToast({
        title: type.value == -1 ? '新增收藏成功' : '编辑收藏成功',
        duration: 1500,
      })
      await new Promise<void>((resolve) => {
        setTimeout(() => {
          resolve
          nextTick(() => {
            uni.navigateBack({})
          })
        }, 1500)
      })
      return
    }
    if (isCallSaveApi.value || isCallApi.value) {
      uni.showToast({
        title: i18n.t('APP.Common.OperationFastWaitTips.Text'),
        duration: 3000,
      })
      return
    }
    isCallSaveApi.value = true
    let curIndexes = curIndex.value[0]
    let millIndexes = millIndex.value[0]
    trackData.value = {
      favoriteName: favoriteName.value,
      currentIndex: currentIndex.value,
      temperatures: temperatures.value[curIndexes].value,
      milliliter: milliliter.value[millIndexes].value / 10,
    }
    if (type.value == -1) {
      addFavorite(
        favoriteName.value,
        currentIndex.value,
        temperatures.value[curIndexes].value,
        milliliter.value[millIndexes].value / 10
      )
    } else {
      editFavorite(
        favoriteName.value,
        currentIndex.value,
        temperatures.value[curIndexes].value,
        milliliter.value[millIndexes].value / 10
      )
    }
  },
})

/**
 * 新增收藏
 * @param name
 * @param fav_pic
 * @param fav_temp
 * @param fav_vol
 */
async function addFavorite(name: string, fav_pic: number, fav_temp: number, fav_vol: number) {
  safeTrack(() => {
    trackEvent(
      'before_favorite_program',
      {
        program_key: control.value?.store.currentProgramKey,
        program_name: control.value?.store.currentProgramName,
        favorite_value_obj: {
          favourite_program_name: name,
          temperature: fav_temp,
          drink_type: favoritePictureList.value[fav_pic].url.split('.')[0],
          volume: fav_vol,
        },
      },
      TrackType.ApplianceDetail,
      'Appliance.BIWD.AddFavorite.Favorite'
    )
  })

  if (!checkHomeApplianceState()) return
  uni.showLoading({
    title: i18n.t('BIWD.AddFavorite.Loading.Add.Text'),
    mask: true,
  })
  let res: any = null
  try {
    let nameArray = NameToArray(name)
    let submitData: submitSettingType[] = []
    if (!isBOSCHBIWD.value) {
      submitData.push(
        {
          key: DatConfig,
          value: DatConfig_SetCollect,
        },
        {
          key: CollectionOperation,
          value: CollectionOperation_Add,
        }
      )
    } else {
      submitData.push({
        key: DatConfig,
        value: DatConfig_AddCollect,
      })
    }
    submitData.push(
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name1',
        value: nameArray[0],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name2',
        value: nameArray[1],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name3',
        value: nameArray[2],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name4',
        value: nameArray[3],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name5',
        value: nameArray[4],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name6',
        value: nameArray[5],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name7',
        value: nameArray[6],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name8',
        value: nameArray[7],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name9',
        value: nameArray[8],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name10',
        value: nameArray[9],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Temp',
        value: fav_temp,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Volume',
        value: fav_vol,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Picture',
        value: fav_pic,
      }
    )
    res = await setHomeApplianceSettings(haId.value, submitData)
    uni.hideLoading()
    uni.navigateBack({
      complete: (res) => {
        isCallSaveApi.value = false
      },
    })
  } catch (error) {
    res = error
    if (favoriteChangeInCallSaveApi) {
      isShowFavoriteUpdateView.value = true
    }
    uni.hideLoading()
    uni.showToast({
      title: '新增收藏失败',
      icon: 'error',
    })
    isCallSaveApi.value = false
  }

  safeTrack(() => {
    trackEvent(
      'favorite_program',
      {
        program_key: control.value?.store.currentProgramKey,
        program_name: control.value?.store.currentProgramName,
        favorite_value_obj: {
          favourite_program_name: name,
          temperature: fav_temp,
          drink_type: favoritePictureList.value[fav_pic].url.split('.')[0],
          volume: fav_vol,
        },
        successOrNot: res.code == 0,
        error_code: res.code,
        response_msg: res.msg,
      },
      TrackType.ApplianceDetail,
      'Appliance.BIWD.AddFavorite.Favorite'
    )
  })
}
/**
 * 编辑收藏
 * @param name
 * @param fav_pic
 * @param fav_temp
 * @param fav_vol
 */
async function editFavorite(name: string, fav_pic: number, fav_temp: number, fav_vol: number) {
  safeTrack(() => {
    trackEvent(
      'before_modify_favorite_program',

      {
        program_key: control.value?.store.currentProgramKey,
        program_name: control.value?.store.currentProgramName,
        favorite_value_obj: {
          favourite_program_name: name,
          temperature: fav_temp,
          drink_type: favoritePictureList.value[fav_pic].url.split('.')[0],
          volume: fav_vol,
        },
      },
      TrackType.ApplianceDetail,
      'Appliance.BIWD.Modifyfavorite.Favorite'
    )
  })

  let res: any = null
  if (!checkHomeApplianceState()) return
  uni.showLoading({
    title: i18n.t('BIWD.AddFavorite.Loading.Edit.Text'),
    mask: true,
  })
  try {
    let nameArray = NameToArray(name)
    let oldNameArray = NameToArray(oldFavoriteName.value)
    let index = Number(type.value) + 1
    let submitData: submitDataType = {
      key: 'BSH.Collect.Program.Selected.FavoriteProgram' + index,
      options: [],
      settings: [],
    }
    if (!isBOSCHBIWD.value) {
      submitData.settings.push(
        {
          key: DatConfig,
          value: DatConfig_SetCollect,
        },
        {
          key: CollectionOperation,
          value: CollectionOperation_Edit,
        }
      )
    } else {
      submitData.settings.push({
        key: DatConfig,
        value: DatConfig_EditCollect,
      })
    }
    submitData.settings.push(
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name1',
        value: nameArray[0],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name2',
        value: nameArray[1],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name3',
        value: nameArray[2],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name4',
        value: nameArray[3],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name5',
        value: nameArray[4],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name6',
        value: nameArray[5],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name7',
        value: nameArray[6],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name8',
        value: nameArray[7],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name9',
        value: nameArray[8],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name10',
        value: nameArray[9],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Temp',
        value: fav_temp,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Volume',
        value: fav_vol,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Picture',
        value: fav_pic,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name1',
        value: oldNameArray[0],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name2',
        value: oldNameArray[1],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name3',
        value: oldNameArray[2],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name4',
        value: oldNameArray[3],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name5',
        value: oldNameArray[4],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name6',
        value: oldNameArray[5],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name7',
        value: oldNameArray[6],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name8',
        value: oldNameArray[7],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name9',
        value: oldNameArray[8],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Name10',
        value: oldNameArray[9],
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Temp',
        value: oldFavoriteTemp.value,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Volume',
        value: oldFavoriteVol.value,
      },
      {
        key: 'WaterTreatment.BIWD.Setting.FavoriteProgram2Picture',
        value: oldFavoritePic.value,
      }
    )
    res = await setHomeAppliancePrograms(haId.value, submitData)
    uni.hideLoading()
    uni.navigateBack({
      complete: (res) => {
        isCallSaveApi.value = false
      },
    })
  } catch (error) {
    res = error
    uni.hideLoading()
    if (favoriteChangeInCallSaveApi) {
      isShowFavoriteUpdateView.value = true
    }
    uni.showToast({
      title: '编辑收藏失败',
      icon: 'error',
    })
    isCallSaveApi.value = false
  }
  safeTrack(() => {
    trackEvent(
      'modify_favorite_program',

      {
        program_key: control.value?.store.currentProgramKey,
        program_name: control.value?.store.currentProgramName,
        favorite_value_obj: {
          favourite_program_name: name,
          temperature: fav_temp,
          drink_type: favoritePictureList.value[fav_pic].url.split('.')[0],
          volume: fav_vol,
        },
        successOrNot: res.code == 0,
        error_code: res.code,
        response_msg: res.msg,
      },
      TrackType.ApplianceDetail,
      'Appliance.BIWD.Modifyfavorite.Favorite'
    )
  })
}
/**
 * 检查净饮器状态
 */
function checkHomeApplianceState() {
  let isCan = true
  if (isCallApi.value == true) {
    //净饮机正在进行api调用
    isCan = false
  } else if (control.value?.store.runState == -1) {
    //获取净饮机状态失败
    isShowErrorView.value = true
    errorText.value = '获取家电运行状态失败'
    isCan = false
  } else if (control.value?.store.runState == 3) {
    //净饮机处于运行状态
    isCan = false
    isShowErrorView.value = true
    errorText.value = '机器正在出水中，暂无法使用小程序控制家电'
  } else if (control.value?.store.isLocalOperate) {
    //净饮机处于本地操作状态
    isCan = false
    isShowErrorView.value = true
    errorText.value = '机器正在被本地操作，暂无法使用小程序控制家电'
  }
  return isCan
}
/**
 *  隐藏错误提示
 */
function hideErrorView() {
  isShowErrorView.value = false
  errorText.value = ''
}
const renamePopFlag = ref(false)
const nameFocus = ref(false)
const nickname = ref('')
/**
 * 打开重命名弹框
 */
function showEditNameView() {
  renamePopFlag.value = true
  nickname.value = favoriteName.value
  nameFocus.value = true
}
//确定重命名
function confirmRename(name: string) {
  if (nameError.value != '') return
  nickname.value = name
  favoriteName.value = name
  cancelRename()
}
//取消重命名
function cancelRename() {
  renamePopFlag.value = false
  nameFocus.value = false
  nickname.value = ''
}
</script>
<style lang="less">
@import '../style/favorite.less';
</style>
